package com.indi.gulimall.product.controller.web;

import com.indi.gulimall.product.entity.CategoryEntity;
import com.indi.gulimall.product.service.CategoryService;
import com.indi.gulimall.product.vo.web.Category2VO;
import io.swagger.annotations.Api;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Api(tags = "首页")
@Controller
public class IndexController {
    @Resource
    private CategoryService categoryService;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        List<CategoryEntity> categories = categoryService.findLevel1Categories();
        model.addAttribute("categories", categories);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/category.json")
    public Map<Long, List<Category2VO>> getCategoryJson() {
        Map<Long, List<Category2VO>> map = categoryService.getCategoryJson();
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        RLock lock = redissonClient.getLock("anyLock");
        try {
            // 阻塞式等待，默认加的锁都是30s时间
            // 如果执行业务时间过长，运行期间会给锁自动续期，每次都会续上30s，不需要担心业务时间过长，导致锁自动删掉
            // 加锁的业务执行完，就不会给当前锁续期，即使不手动释放锁，锁默认也会在30s以后自动删除
            lock.lock();
            try {
                System.out.println("加锁成功，执行业务..." + Thread.currentThread().getId());
                TimeUnit.SECONDS.sleep(30);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } finally {
            lock.unlock();
            System.out.println("释放锁..." + Thread.currentThread().getId());
        }
        return "hello";
    }

    @ResponseBody
    @GetMapping("/read")
    public String read() {
        String uuid = "";
        RLock rLock = redissonClient.getReadWriteLock("rwAnyLock").readLock();
        try {
            rLock.lock();
            System.out.println("读锁加锁成功" + Thread.currentThread().getId());
            uuid = stringRedisTemplate.opsForValue().get("writeValue");
            TimeUnit.SECONDS.sleep(30);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
            System.out.println("读锁释放成功" + Thread.currentThread().getId());
        }
        return uuid;
    }

    @ResponseBody
    @GetMapping("/write")
    public String write() {
        RLock rLock = redissonClient.getReadWriteLock("rwAnyLock").writeLock();
        String uuid = "";
        try {
            rLock.lock();
            System.out.println("写锁加锁成功" + Thread.currentThread().getId());
            uuid = UUID.randomUUID().toString();
            stringRedisTemplate.opsForValue().set("writeValue", uuid);
            TimeUnit.SECONDS.sleep(30);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
            System.out.println("写锁释放成功" + Thread.currentThread().getId());
        }
        return uuid;
    }

    @ResponseBody
    @GetMapping("/park")
    public String park() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.acquire();
        return "停车位-1";
    }

    @ResponseBody
    @GetMapping("/try-park")
    public String tryPark() {
        RSemaphore park = redissonClient.getSemaphore("park");
        boolean result = park.tryAcquire();
        if (result) {
            return "停车位-1";
        } else {
            return "停车位已满";
        }
    }

    @ResponseBody
    @GetMapping("/go")
    public String go() {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();
        return "空闲车位+1";
    }

    @ResponseBody
    @GetMapping("/go-home/{id}")
    public String goHome(@PathVariable Integer id) {
        RCountDownLatch home = redissonClient.getCountDownLatch("home");
        home.countDown();
        return id + "班已走";
    }

    @ResponseBody
    @GetMapping("/lock-door")
    public String lockDoor() throws InterruptedException {
        RCountDownLatch home = redissonClient.getCountDownLatch("home");
        home.await();
        return "锁门";
    }

}
